import plugin from '../../lib/plugins/plugin.js'
import common from '../../lib/common/common.js'
import fs from 'fs'
const _path = process.cwd()

export class example extends plugin {
    constructor() {
        super({
            name: "统计功能触发次数",
            dsc: "",
            event: "message",
            priority: 1000,
            rule: [
                {
                    reg: "^#?(任务|函数|插件功能使用|功能(使用|触发)|功能)统计$",
                    fnc: "statistics"
                },
                {
                    reg: "^#?(任务|函数|插件功能使用|功能(使用|触发)|功能)(全部统计|统计全部)$",
                    fnc: "all"
                }

            ]
        })
    }
    //qq2066855608
    async all() {
        const logDir = `${_path}/logs`
        const logFiles = fs.readdirSync(logDir).filter(file => file.includes('command') && !file.includes('error'))
      
        const taskCounts = {}
        //避免瞬间满载
        for (const logFile of logFiles) {
          const data = await fs.promises.readFile(`${logDir}/${logFile}`, 'utf8')
          const dataArray = data.split('\n')
          for (let i = 0; i < dataArray.length; i++) {
            const line = dataArray[i]
            if (line.includes('[MARK]') && line.includes('[') && line.includes(']') && !line.includes('处理完成')) {
              const matched = line.match(/\[(.*?)\]/g)
              if (matched && matched.length >= 3) {
                const taskName = matched[2].slice(1, -1)
                if (line.includes('[MARK]')) {
                  if (!taskCounts[taskName]) {
                    taskCounts[taskName] = 0
                  }
                  taskCounts[taskName]++
                }
              }
            }
          }
        }
      
        const taskCountsArray = []
        for (const taskName in taskCounts) {
          taskCountsArray.push({ name: taskName, count: taskCounts[taskName] })
        }
        taskCountsArray.sort((a, b) => b.count - a.count)
        const taskCountsString = taskCountsArray.map(task => `${task.name}: ${task.count}次`).join('\n')
        this.reply(await common.makeForwardMsg(this.e, [taskCountsString], '全部日志功能触发统计'))
      }


    

    async statistics() {

        const currentDate = await getCurrentTime()
        const logPath = `${_path}/logs/command.${currentDate}.log`
        const data = fs.readFileSync(logPath, 'utf8')
        const dataArray = data.split('\n')
        const taskCounts = {}
        for (let i = 0; i < dataArray.length; i++) {

            const line = dataArray[i]
            if (line.includes('[MARK]') && line.includes('[') && line.includes(']') && !line.includes('处理完成')) {
                const matched = line.match(/\[(.*?)\]/g)
                if (matched && matched.length >= 3) {
                    const taskName = matched[2].slice(1, -1)
                    if (line.includes('[MARK]')) {
                        if (!taskCounts[taskName]) {
                            taskCounts[taskName] = 0
                        }
                        taskCounts[taskName]++
                    }
                }
            }
        }

        const taskCountsArray = []
        for (const taskName in taskCounts) {
            taskCountsArray.push({name: taskName, count: taskCounts[taskName]})
        }
        taskCountsArray.sort((a, b) => b.count - a.count)
        const taskCountsString = taskCountsArray.map(task => `${task.name}: ${task.count}次`).join('\n')
        this.reply(await common.makeForwardMsg(this.e, [taskCountsString], `${currentDate}功能触发次数统计：`))
    }

}







async function getCurrentTime() {
    const currentDate = new Date()
    const year = currentDate.getFullYear()
    const month = (currentDate.getMonth() + 1).toString().padStart(2, '0')
    const day = currentDate.getDate()
    return `${year}-${month}-${day}`
}



